<template>
  <my-container>
    <template #header>
      <vxe-toolbar perfect>
        <template v-slot:buttons>
          <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
            <el-form-item>
              <el-input
                v-model="filter.name"
                placeholder="任务名称"
                clearable
                @keyup.enter.native="getTaskListPage"
              >
                <template #prefix>
                  <i class="el-input__icon el-icon-search" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="checkPermission(['api:quality:machinecheck:getownerpage'])">
              <el-button icon="el-icon-search" type="primary" @click="getTaskListPage">查询</el-button>
            </el-form-item>
          </el-form>
        </template>
      </vxe-toolbar>
    </template>
    <vxe-table
      ref="xcTable"
      :loading="listLoading"
      border
      size="small"
      :keep-source="true"
      :auto-resize="true"
      :edit-config="{trigger: 'manual', mode: 'row', showStatus: true, icon: 'fa fa-file-text-o'}"
      stripe
      highlight-hover-row
      resizable
      :edit-rules="{ actualBeginDate: [
                       { required: true, message: '开始时间不可为空' }
                     ],
                     actualEndDate: [
                       { required: true, message: '预计结束时间不可为空' }
                     ] }"
      :data="tableData"
    >
      <vxe-table-column
        type="seq"
        width="60"
      />
      <vxe-table-column
        field="projectName"
        show-overflow
        title="项目名称"
      />
      <vxe-table-column
        field="parentName"
        title="阶段名称"
      />
      <vxe-table-column
        field="taskName"
        title="任务名称"
      />
      <vxe-table-column
        field="planBeginDate"
        title="计划开始时间"
      >
        <template v-slot="{ row }">
          <span>{{ formatDate(row.planBeginDate) }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column
        field="planEndDate"
        title="计划结束时间"
      > <template v-slot="{ row }">
        <span>{{ formatDate(row.planEndDate) }}</span>
      </template>
      </vxe-table-column>
      <vxe-table-column
        field="actualBeginDate"
        title="开始时间"
        :edit-render="{name: '$input', props: {type: 'date'}}"
      />
      <vxe-table-column
        field="actualEndDate"
        title="预计结束时间"
        :edit-render="{name: '$input', props: {type: 'date'}}"
      />
      <vxe-table-column
        field="progress"
        title="任务进度"
      >
        <template v-slot="{ row }">
          <el-progress :percentage="row.progress" :color="customColorMethod" />
          <!-- <el-progress :text-inside="true" :stroke-width="24" :percentage="row.progress*100" /> -->
        </template>
      </vxe-table-column>
      <vxe-table-column
        field="responName"
        title="责任人"
      />
      <vxe-table-column
        field="taskFlag"
        title="任务状态"
      >  <template v-slot="{ row }">
        <el-tag v-if="row.taskFlag!=null" :type="row.taskFlag =='未处理'?'info':row.taskFlag =='处理中'?'warning':row.taskFlag =='已完成'?'success':'' ">{{ row.taskFlag }}</el-tag>
      </template>
      </vxe-table-column>
      <vxe-table-column
        field="remark"
        title="备注"
      />
      <vxe-table-column title="操作" width="160">
        <template v-slot="{ row }">
          <template v-if="$refs.xcTable.isActiveByRow(row)">
            <vxe-button @click="saveRowEvent(row)">确认</vxe-button>
            <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
          </template>
          <template v-else>
            <template v-if="row.taskFlag =='待处理'">
              <vxe-button @click="editRowEvent(row)">开启</vxe-button>
            </template>
            <template v-else-if="row.taskFlag =='处理中'">
              <vxe-button @click="onEdit(row)">更新</vxe-button>
            </template>
            <template v-else />
          </template>
        </template>
      </vxe-table-column>
    </vxe-table>
    <template #footer>
      <vxe-pager
        perfect
        :current-page.sync="tablePage.currentPage"
        :page-size.sync="tablePage.pageSize"
        :total="tablePage.total"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]"
        @page-change="pageChange"
      />
    </template>

    <vxe-modal
      v-if="checkPermission(['api:quality:checkresport:update'])"
      v-model="editFormVisible"
      :loading="submitLoading"
      title="更新任务"
      width="500"
      height="445"
      destroy-on-close
      resize
    >
      <template v-slot>
        <vxe-form ref="formtask" :data="editForm" :rules="editFormRules" title-align="right" title-width="120" @submit="onEditSubmit">
          <vxe-form-item title="预计结束时间" field="actualEndDate" span="24" :item-render="{name: '$input', props: { type: 'date', placeholder: '请选择日期' }}" />
          <vxe-form-item title="处理结果" field="taskFlag" span="24" :item-render="{name: 'ElSelect', options: typeList, events: { change: changeValue }}" />
          <vxe-form-item v-if="editForm.taskFlag==1" title="任务进度" field="progress" span="24">
            <div class="block">
              <el-slider
                v-model="editForm.progress"
                show-input
              />
            </div>
          </vxe-form-item>
          <vxe-form-item title="描述" field="remark" span="24">
            <vxe-textarea v-model="editForm.remark" placeholder="请输入进度描述" size="small" />
          </vxe-form-item>

          <vxe-form-item title="文档上传" field="filePath" span="24" :title-prefix="{ message: '上传形成的文档！！！' }">
            <template v-slot>
              <el-upload
                v-loading="calLoading"
                class="avatar-uploader"
                action="/api/quality/checkresport/fileupload"
                :limit="1"
                :headers="token"
                :before-upload="()=>{calLoading = true}"
                :on-success="oncalSuccess"
                :on-error="oncalError"
                style="display: inline-block;"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">限上传一个，只能上传xls/xlsx/docx/doc文件,不能超过10M</div>
              </el-upload>
            </template>
          </vxe-form-item>
          <vxe-form-item align="right" span="24">
            <vxe-button @click="editclose()">取消</vxe-button>
            <vxe-button type="submit" status="primary">更新</vxe-button>
          </vxe-form-item>
        </vxe-form>
      </template>
      <!-- <template v-slot:footer>
        <vxe-button @click="editclose()">取消</vxe-button>
        <vxe-button type="submit" status="primary" @click="onEditSubmit()">提交</vxe-button>
      </template> -->
    </vxe-modal>

  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { getTaskListPage, taskBegin, updateTask, getUpTask } from '@/api/project/taskrun'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Stocklist',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        name: ''
      },
      tableData: [],
      typeList: [
        { label: '处理中', value: 1 },
        { label: '已完成', value: 2 }
      ],
      editFormRules: {
        actualEndDate: [{ required: true, message: '请输入校验时间', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入校验描述', trigger: 'blur' }]
      },
      tableToolbar: {
        custom: true,
        export: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      submitLoading: false,
      proxyConfig: {
        seq: true, // 启用动态序号代理
        props: {
          result: 'result',
          total: 'page.total'
        },
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）, sort, filters, form
          query: async({ page }) => {
            // 处理排序条件
            const para = {
              currentPage: this.tablePage.currentPage, // page.currentPage
              pageSize: this.tablePage.pageSize, // page.pageSize
              filter: this.filter
            }
            this.listLoading = true
            const res = await getTaskListPage(para)
            this.listLoading = false
            if (!res?.success) {
              return
            }
            this.tablePage.total = res.data.page.total
            if (!res?.success) {
              return
            }
            return res.data
          },
          // 被某些特殊功能所触发，例如：导出数据 mode=all 时，会触发该方法并对返回的数据进行导出
          queryAll: () => getAllPage({ name: this.filter.name, id: this.filter.xbcTypeId
          })
        }
      },
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      listLoading: false,
      editFormVisible: false, // 编辑界面是否显示
      // 编辑界面数据
      editForm: {
        taskId: null,
        actualEndDate: null, // 校验时间
        fileName: '',
        remark: '', // 描述
        progress: 0,
        taskFlag: 1,
        filePath: '' // 检验报告
      },
      customColor: '#409eff',
      avatarLoading: false,
      calLoading: false
    }
  },
  computed: {
    token() {
      return { 'Authorization': 'Bearer ' + this.$store.getters.token }
    }
  },
  mounted() {
    this.getTaskListPage()
  },
  methods: {
    formatDate(cellValue) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    // 上传成功
    onAvatarSuccess(res) {
      this.avatarLoading = false
      if (!res?.code === 1) {
        return
      }
      // console.log('f', res.data)
      this.addForm.filePath = res.data
    },
    // 上传失败
    onAvatarError(err, file) {
      this.avatarLoading = false
      const res = err.message ? JSON.parse(err.message) : {}
      if (!(res?.code === 1)) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    },
    // 上传成功
    oncalSuccess(res, ff) {
      this.calLoading = false
      if (!res?.code === 1) {
        return
      }
      this.editForm.filePath = res.data
      this.editForm.fileName = ff.name
    },
    // 上传失败
    oncalError(err, file) {
      this.calLoading = false
      const res = err.message ? JSON.parse(err.message) : {}
      if (!(res?.code === 1)) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    },
    async getTaskListPage() {
      const para = {
        currentPage: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize,
        filter: this.filter
      }
      this.listLoading = true
      const res = await getTaskListPage(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      this.tablePage.total = res.data.total
      const data = res.data.list
      this.tableData = data
    },
    async pageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
    },
    // 汇总列表
    async  getMachineCheckList() {
      if (this.$refs.xGrid) {
        this.$nextTick(() => {
          this.$refs.xGrid.commitProxy('reload')
        })
      }
    },
    // 编辑
    async onEditSubmit() {
      this.submitLoading = true
      const para = _.cloneDeep(this.editForm)
      const res = await updateTask(para)
      this.submitLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: '更新完成!',
        type: 'success'
      })
      this.editFormVisible = false
      this.getTaskListPage()
    },
    editRowEvent(row) {
      this.$refs.xcTable.setActiveRow(row)
    },
    cancelRowEvent(row) {
      const xTable = this.$refs.xcTable
      xTable.clearActived().then(() => {
        // 还原行数据
        xTable.revertData(row)
      })
    },
    async changeValue() {
      if (this.editForm.taskFlag === 1) {
        this.editFormRules = {
          actualEndDate: [{ required: true, message: '请输入校验时间', trigger: 'blur' }],
          remark: [{ required: true, message: '请输入校验描述', trigger: 'blur' }]
        }
      } else if (this.editForm.taskFlag === 2) {
        this.editFormRules = {
          actualEndDate: [{ required: true, message: '请输入校验时间', trigger: 'blur' }],
          remark: [{ required: true, message: '请输入校验描述', trigger: 'blur' }],
          filePath: [{ required: true, message: '请添加附件', trigger: 'blur' }]
        }
      }
    },
    async  saveRowEvent(row) {
      const {
        insertRecords,
        // eslint-disable-next-line no-unused-vars
        removeRecords,
        // eslint-disable-next-line no-unused-vars
        updateRecords
      } = this.$refs.xcTable.getRecordset()
      console.log('err', updateRecords)
      if (updateRecords.length !== 0) {
        this.$refs.xcTable.validate(async(errMap) => {
          if (errMap) {
            this.$XModal.message({ status: 'error', message: '校验不通过！' })
          } else {
            this.$refs.xcTable.clearActived().then(() => {
              this.loading = true
              setTimeout(async() => {
                var res = await taskBegin(updateRecords[0])
                if (res && res.success) {
                  this.loading = false
                  this.getTaskListPage()
                  this.$XModal.message({ status: 'success', message: '开启成功！' })
                }
              }, 100)
            })
          }
        })
      } else {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      }
    },
    // 新增验证
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 显示编辑界面
    async onEdit(row) {
      if (row.taskFlag === '处理中') {
        this.editFormVisible = true
        this.submitLoading = true
        const res = await getUpTask({ id: row.id })
        if (res && res.success) {
          const data = res.data
          this.editForm = data
        }
        this.submitLoading = false
      } else {
        this.$message({
          message: '异常状态业务待确认',
          type: 'warning'
        })
      }
    },
    closeEditForm() {
    },

    // 编辑验证
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    editclose() {
      this.editFormVisible = false
    },
    selsChange: function(sels) {
      this.sels = sels
    }
  }
}
</script>
